<template>
	<view class="content" :style="[getpaddingTop]">
		<!-- 主tab切换区 -->
		<view class="mainTabBox">
			<button
				v-for="(tab, idx) in mainTabList"
				:key="idx"
				:class="['mainTabBtn', mainTabIndex === idx ? 'active' : '']"
				@click="switchMainTab(idx)"
			>{{ tab }}</button>
		</view>
		<!-- 二级tab切换区 -->
		<view class="navTabBox" >
			<view class="longTab">
				<scroll-view scroll-x="true" style="white-space: nowrap; display: flex;" scroll-with-animation
					:scroll-left="tabLeft" show-scrollbar="true">
					<view class="longItem" :data-index="index" :class="index===tabClick?'click':''"
						v-for="(item,index) in currentSubTabList" :key="index" :id="'id'+index" @click="longClick(index,item)">
						{{ item.title }} <span v-if="item.total"> {{'('+item.total+')'}}</span>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class='return-list borderPad' v-if="orderList.length">
			<return-list :orderList="orderList" @goDetails="goReturnDetails"></return-list>
		</view>
		
		<!-- 空状态显示 -->
		<view class="empty-state" v-if="!loading && orderList.length === 0 && isShow">
			<view class="empty-icon">
				<text class="iconfont icon-wushuju"></text>
			</view>
			<view class="empty-text">
				<text>暂无售后订单</text>
			</view>
			<view class="empty-tip">
				<text>下拉刷新试试</text>
			</view>
		</view>

	</view>
</template>
<script>
	import returnList from '@/components/base/return-list.vue'
	import orderList from '@/components/base/order-list.vue'
	import getList from '@/mixins/getlist.js'
	import {
		orderAuditApi,
		orderRejectApi,
		saleRoomRefundOrderList
	} from '@/api/index.js'

	export default {
		components: {
			orderList,
			returnList
		},
		filters: {
			orderRefundTipsStatusFilter(status) {
				const statusMap = {
					0: '退款前请与商家协商一致,有助于更好的处理售后问题。',
					1: '若有异议，请联系平台处理。',
					2: '商家已同意您的退款,若您已收到商品请您尽快退回，7天内未发出,系统自动撤销售后单，感谢您对我们的支持!',
					3: '商家已为您退款，若商家已寄出商品请您尽快寄回，感谢您对我们的支持!',
					4: '商家已同意您的退款,若您已收到商品请您尽快退回，7天内未发出,系统自动撤销售后单，感谢您对我们的支持!',
					5: '商家确认收货后进行退款,请您耐心等待，若有异议请联系平台客服处理!',
					6: '此退款单已撤销，若对此订单存在疑问，请联系商家协商处理。',
				}
				return statusMap[status]
			},
			refundStatusFilter(status) {
				const statusMap = {
					0: '商家审核中',
					1: '商家已拒绝',
					2: '商家已同意，退款中',
					3: '退款成功',
					4: '商家已同意',
					5: '等待商家收货并退款',
					6: '撤销申请',
					// 0: '未退款',
					// 1: '申请中',
					// 2: '部分退款',
					// 3: '已退款'
				}
				return statusMap[status]
			}

		},
		mixins: [getList],
		data() {
			return {
				isLoading: false,
				isFixed: true,
				tabClick: 0,
				tabLeft: 0,
				mainTabList: ['退货管理'],  //'换货管理'
				mainTabIndex: 0,
				subTabList: [
					[
						{ title: '全部', type: -1 },
						{ title: '待审核', type: 0 },
						{ title: '配送员拒绝', type: 1 },
						// { title: '退款中', type: 2 },
						{ title: '已退款', type: 3 },
						// { title: '用户退货', type: 4 },
						// { title: '商家待收货', type: 5 },
						{ title: '已撤销', type: 6 },
						{ title: '待上门', type: 7 },
						{ title: '上门中', type: 8 }
					],
					[
						{ title: '全部', type: -1 },
						{ title: '待审核', type: 0 },
						{ title: '配送员拒绝', type: 1 },
						{ title: '退款中', type: 2 },
						{ title: '已退款', type: 3 },
						{ title: '用户退货', type: 4 },
						{ title: '商家待收货', type: 5 },
						{ title: '已撤销', type: 6 },
						{ title: '待上门', type: 7 },
						{ title: '上门中', type: 8 }
					]
				],
				refundTypeStatus: 0,
				isRefreshing: false,
				lastRefreshTime: 0
			}
		},
		onLoad() {
			uni.getSystemInfo({
				success: function(e) {
					console.log(e.windowTop, 39);
					this.windowTop = e.windowTop
				}
			})
			
			// 监听网络状态变化
			uni.onNetworkStatusChange((res) => {
				if (!res.isConnected) {
					uni.showToast({
						title: '网络连接已断开',
						icon: 'none',
						duration: 2000
					});
				}
			});
		},
		onShow() {
			this.getOrderList()
		},
		computed: {
			getpaddingTop() {
				return {
					paddingTop: this.windowTop * 2 + 'px',
				}
			},
			currentSubTabList() {
				return this.subTabList[this.mainTabIndex];
			},
			returnGoodsType() {
				return this.mainTabIndex + 1;
			},
			refundStatus() {
				return this.currentSubTabList[this.tabClick].type;
			},
			getTabType() {
				return this.currentSubTabList[this.tabClick].type;
			}

		},
		methods: {
			goReturnDetails(item){
				uni.navigateTo({
					url: '/pages/returnDetails/returnDetails?refundOrderNo=' + item.refundOrderNo
				})
			},
			refusedTheRefund(item) {
				let that = this
				uni.showModal({
					placeholderText: '请输入拒绝原因',
					editable: true,
					success: function(res) {
						if (res.confirm) {
							orderRejectApi({
								auditType: 'refuse',
								reason: res.content,
								refundOrderNo: item.refundOrderNo
							}).then(ress => {
								uni.showToast({
									icon: 'none',
									title: '已拒绝'
								})
								that.loadend = false
								that.loading = false
								that.page = 1
								that.orderList = []
								that.getOrderList()
							}).catch(e => {
								uni.showToast({
									title: e,
									icon: 'error'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			agreedToRefund(item) {
				let that = this
				uni.showModal({
					title: '同意',
					content: '确认同意退款吗？',
					success: function(res) {
						if (res.confirm) {
							orderAuditApi({
								auditType: 'success',
								refundOrderNo: item.refundOrderNo,
							}).then(ress => {
								if (ress.data) {
									uni.showToast({
										icon: 'none',
										title: '已审核'
									})
								}
								that.loadend = false
								that.loading = false
								that.page = 1
								that.orderList = []
								that.getOrderList()
							}).catch(e => {
								uni.showToast({
									title: e,
									icon: 'error'
								})
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			goDetails(item) {
				uni.navigateTo({
					url: '/pages/orderDetails/orderDetails?orderNo=' + item.orderNo
				})
			},
			onPullDownRefresh() {
				// 防抖处理：3秒内只能刷新一次
				const now = Date.now();
				if (now - this.lastRefreshTime < 3000) {
					uni.stopPullDownRefresh();
					uni.showToast({
						title: '请稍后再试',
						icon: 'none',
						duration: 1500
					});
					return;
				}
				
				this.lastRefreshTime = now;
				
				// 设置刷新状态
				this.isRefreshing = true;
				
				// 重置加载状态
				this.loadend = false;
				this.loading = false;
				this.page = 1;
				this.orderList = [];
				
				// 显示加载提示
				uni.showLoading({
					title: '刷新中...',
					mask: true
				});
				
				// 调用获取订单列表方法
				this.getOrderList().then(res => {
					// 隐藏加载提示
					uni.hideLoading();
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
					// 显示成功提示
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					});
				}).catch(err => {
					// 隐藏加载提示
					uni.hideLoading();
					// 停止下拉刷新动画
					uni.stopPullDownRefresh();
					// 显示错误提示
					uni.showToast({
						title: err.message || '刷新失败，请重试',
						icon: 'error',
						duration: 2000
					});
					console.error('下拉刷新失败:', err);
				});
			},

			/**
			 * 切换类型
			 */
			switchMainTab(idx) {
				this.mainTabIndex = idx;
				this.tabClick = 0;
					// 重置加载状态
				this.loadend = false;
				this.loading = false;
				this.page = 1;
				this.orderList = [];
				this.getOrderList();
			},
			longClick(index, item) {
				if (index == this.tabClick) return;
				this.tabClick = index;
				this.loadend = false;
				this.page = 1;
				this.orderList = [];
				this.getOrderList();
				this.isLoading = true;
				setTimeout(() => {
					this.isLoading = false;
				}, 2000);
				this.$nextTick(() => {
					let id = 'id' + index;
					this.tabLeft = (index - 2) * this.isWidth;
				});
			},
			getOrderList() {
				return new Promise((resolve, reject) => {
					let that = this;
					
					// 如果是下拉刷新，跳过这些检查
					if (!that.isRefreshing) {
						if (that.loadend) return reject( ('已加载全部数据'));
						if (that.loading) return reject( ('正在加载中'));
					}
					
					that.loading = true;
					that.loadTitle = "加载更多";
					
					saleRoomRefundOrderList({
						page: that.page,
						limit: that.limit,
						returnGoodsType: this.returnGoodsType,
						refundStatus: this.refundStatus
					}).then(res => {
						// 验证返回数据
						if (!res || !res.data) {
							throw new Error('返回数据格式错误');
						}
						
						let list = res.data.list || [];
						let loadend = list.length < that.limit;
						
						// 如果是下拉刷新（第一页），直接替换数据
						if (that.page === 1) {
							that.orderList = list;
						} else {
							// 否则追加数据
							that.orderList = that.$util.SplitArray(list, that.orderList);
						}
						
						that.$set(that, 'orderList', that.orderList);
						that.loadend = loadend;
						that.loading = false;
						that.loadTitle = loadend ? "我也是有底线的" : '加载更多';
						that.page = that.page + 1;
						that.isShow = true;
						
						// 重置刷新状态
						that.isRefreshing = false;
						
						resolve(true);
					}).catch(err => {
						that.loading = false;
						that.loadTitle = "加载更多";
						that.isRefreshing = false;
						
						// 如果是网络错误，给出更友好的提示
						let errorMsg = '网络请求失败';
						if (err.message) {
							errorMsg = err.message;
						}
						
						reject(new Error(errorMsg));
					});
				});
			},
		}
	}
</script>

<style scoped lang="scss">
	.navTabBox {
		// height: 60rpx;
		padding: 8rpx 0;
	}

	.content {
		height: 100vh;
		background: #F5F5F5;
		box-sizing: border-box;
		// padding: 100rpx 30rpx 60rpx 30rpx;
	}

	.isFixed {
		z-index: 10;
		position: fixed;
		background: #F5F5F5;
		left: 0;
		width: 100%;
		/* #ifdef H5 */
		top: 100rpx;
		/* #endif */
		/* #ifdef APP */
		top: 0;
		/* #endif */
	}

	.mainTabBox {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 32rpx 0 12rpx 0;
		gap: 16rpx;
	}

	.mainTabBtn {
		padding: 0 32rpx;
		height: 56rpx;
		line-height: 56rpx;
		border-radius: 8rpx;
		background: #f2f2f2;
		color: #333;
		font-size: 28rpx;
		border: none;
		outline: none;
		margin: 0 8rpx;
		transition: background 0.2s, color 0.2s;
	}

	.mainTabBtn.active {
		background: #1677ff;
		color: #fff;
	}

	.longTab {
		.longItem {
			font-size: 30rpx;
			color: #333;
			padding: 0 32rpx;
			height: 60rpx;
			line-height: 60rpx;
			display: inline-block;
			position: relative;
			cursor: pointer;

			&.click {
				color: #1677ff;
				font-weight: bold;
			}

			&.click::after {
				content: '';
				display: block;
				width: 60%;
				height: 4rpx;
				background: #1677ff;
				border-radius: 2rpx;
				position: absolute;
				left: 20%;
				bottom: 0;
			}
		}
	}

	.return-list {
		width: calc(88%) !important;
		margin: 120rpx auto;
	}

	.return-list .goodWrapper {
		background-color: #fff;
		margin-top: 20rpx;
		position: relative;
		padding: 0rpx 24rpx 20rpx 24rpx;
	}

	.return-list .goodWrapper .orderNum {
		border-bottom: 1px solid #eee;
		height: 86rpx;
		line-height: 86rpx;

		.tit {
			font-size: 28rpx;
			color: #282828;
		}

		.no {
			font-size: 28rpx;
			color: #282828;
		}
	}

	.return-list .goodWrapper .item {
		border-bottom: 0;
		padding: 25rpx 0;

		.money {
			color: #999999;
			font-weight: 26rpx;
			margin-top: 0;
		}

		.attr,
		.num {
			font-size: 20rpx;
			color: #999999;
			margin-top: 0;
		}
	}

	.return-list .goodWrapper .totalSum {
		padding: 0 0 32rpx 0;
		// text-align: right;
		font-size: 26rpx;
		color: #282828;
		display: flex;
		justify-content: space-between;
	}

	.return-list .goodWrapper .totalSum .price {
		font-size: 28rpx;
		font-weight: bold;
		// @include price_color(theme);
	}

	.hui {
		color: #CCCCCC;
		font-size: 24rpx;
	}

	.return-list .goodWrapper .powder {
		// @include price_color(theme);
		//font-size: 24rpx;
	}

	.align-center {
		margin-top: 32rpx;
	}

	.noCart {
		margin-top: 32%
	}

	.pictrue image {
		width: 120rpx;
		height: 120rpx;
	}

	.default_txt {
		font-size: 26rpx;
		color: #999;
		text-align: center;
	}

	.font-color {
		color: #e93323 !important
	}

	.setbtn {
		border: 1px solid #1296db;
		color: #fff;
		background: #1296db;
		width: 160rpx;
		height: 60rpx;
		text-align: center;
		line-height: 60rpx;
		color: #fff;
		border-radius: 50rpx;
		font-size: 26rpx;
	}
	
	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 200rpx 0;
		text-align: center;
	}
	
	.empty-icon {
		margin-bottom: 40rpx;
	}
	
	.empty-icon .iconfont {
		font-size: 120rpx;
		color: #CCCCCC;
	}
	
	.empty-text {
		margin-bottom: 20rpx;
	}
	
	.empty-text text {
		font-size: 32rpx;
		color: #666666;
		font-weight: 500;
	}
	
	.empty-tip text {
		font-size: 26rpx;
		color: #999999;
	}
</style>
